<?php
/**
 * Created by PhpStorm.
 * User: CY
 * Date: 2018/3/6
 * Time: 9:17
 */

namespace app\api\validate;

use app\lib\exception\ParamterException;
use think\Request;
use think\Validate;

class BaseValidate extends Validate
{
    /**
     * 检测所有客户端发来的参数是否符合验证类规则
     * @return bool
     * @throws ParamterException
     */
    public function goCheck(){
        // 必须设置content-type:application/json
        $request = Request::instance();
        $params = $request->param();
        // 获得token
        $params['token'] = $request->header('token');

        // 验证未通过
        if(!$this->check($params)){
            $exception = new ParamterException(
                [
                    'msg' => is_array($this->error) ? implode(';',$this->error) : $this->error
                ]
            );
            throw $exception;
        }else{
            // 验证通过
            return true;
        }
    }

    /**
     * @param $arrays $arrays按照rule过滤后返回数组
     * @return array
     * @throws ParamterException
     */
    public function getDataByRule($arrays){
        if(array_key_exists('user_id',$arrays) | array_key_exists('uid',$arrays)){
            throw new ParamterException([
                'msg' => '参数中包含有非法的参数名user_id或者uid'
            ]);
        }
        $newArray = [];
        foreach ($this->rule as $key => $value){
            $newArray[$key] = $arrays[$key];
        }
        return $newArray;
    }

    /**
     * 正整数验证
     * @param $value
     * @param string $rule
     * @param string $data
     * @param string $field
     * @return bool|string
     */
    protected function isPositiveInteger($value,$rule = '',$data = '',$field = ''){
        if(is_numeric($value) && is_int($value + 0) && ($value + 0) > 0){
            return true;
        }else{
            return $field . '必须是正整数';
        }
    }

    /**
     * 不为空验证
     * @param $value
     * @param string $rule
     * @param string $data
     * @param string $field
     * @return bool|string
     */
    protected function isNotEmpty($value,$rule = '',$data = '',$field = ''){
        if(empty($value)){
            return $field . '不允许为空';
        }

        return true;
    }

    /**
     * 手机号验证
     * @param $value
     * @return bool
     */
    protected function isMobile($value){
        $rule = '^1(3|4|5|7|8)[0-9]\d{8}$^';
        $result = preg_match($rule,$value);
        if($result){
            return true;
        }else{
            return false;
        }
    }

}